//
//  PublicUtils.m
//  EFHealth
//
//  Created by liumadu on 14-12-5.
//  Copyright (c) 2018年 ef. All rights reserved.
//

#import "PublicUtils.h"
#import "AppMacro.h"
//#import "UtilsMacro.h"

#import "UIView+Ext.h"


#import <CommonCrypto/CommonDigest.h>

@implementation PublicUtils
#pragma mark - 密码加密
+(NSString *)encode:(NSString *)pwd
{
    if (pwd==nil||pwd.length==0)    return @"";
    
    NSMutableString *ss=[NSMutableString string];
    for (int i=0; i<pwd.length; i++) {
        [ss appendFormat:@"$%d1;",[pwd characterAtIndex:i]];
    }
    return ss;
}

+ (BOOL)nickNameCheck:(NSString *)nickName
{
    NSString *nicknameRegex = @"^[\u4e00-\u9fa5a-zA-Z0-9_]+$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
    
    BOOL b = [passWordPredicate evaluateWithObject:nickName] ;
   
    return b;
}
+ (BOOL)passWordCheck:(NSString *)passWord
{
    NSString *passWordRegex = @"^[a-zA-Z0-9]{6,20}+$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
   
    BOOL isPass = [passWordPredicate evaluateWithObject:passWord];
    
    return isPass ;
}

#pragma mark - 根据颜色创建图片
+ (UIImage *)createImageWithColor:(UIColor *)color
{
  CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
  UIGraphicsBeginImageContext(rect.size);
  CGContextRef context = UIGraphicsGetCurrentContext();
  CGContextSetFillColorWithColor(context, [color CGColor]);
  CGContextFillRect(context, rect);
  UIImage*theImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return theImage;
}

#pragma mark- 16进制颜色转换
+ (UIColor *) colorWithHexString: (NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}

#pragma mark - 改变图片的颜色
+ (UIImage *) imageWithTintColor:(UIImage *)image color:(UIColor *)tintColor
{
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0f);
    [tintColor setFill];
    CGRect bounds = CGRectMake(0, 0, image.size.width, image.size.height);
    UIRectFill(bounds);
    
    //改变颜色
    [image drawInRect:bounds blendMode:kCGBlendModeDestinationIn alpha:1.0f];
    
    UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return tintedImage;
}

#pragma mark - 根据文字计算label的宽度
+ (CGFloat)getLabelWidthWithString:(NSString *)string font:(UIFont *)font{
    
    return  [string sizeWithAttributes:@{NSFontAttributeName:font}].width;
}

#pragma mark - 根据string的 label宽度 字体大小 行间距 计算所需高度
+ (CGFloat)heightWithString:(NSString *)string width:(CGFloat)width fontSize:(int)font lineSpace:(int)lineSpace
{
    if (string == nil)    return 0 ;
    if (width== 0)  width = SCREEN_WIDTH-kEdgeDoubleWidth ;
    if (font == 0) font = 15 ;
    if (lineSpace == 0) lineSpace = 3 ;
    
    UILabel *label = [[UILabel alloc]init];
    label.numberOfLines = 0 ;
    label.width = width;
    label.font = [UIFont systemFontOfSize:font];
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:string];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpace];//调整行间距
    [text addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0,string.length)];
    [label setAttributedText:text];
    [label sizeToFit];
    return label.height;
}

#pragma mark - 根据文字计算高度
+ (CGFloat)getStringSizeWith:(NSString *)str Width:(CGFloat)width Font:(UIFont *)font
{
    CGRect rect = [str
                   boundingRectWithSize:CGSizeMake(width, 0)
                   options:NSStringDrawingUsesLineFragmentOrigin
                   attributes:@{NSFontAttributeName:font}
                   context:nil];
    return rect.size.height ;
}
#pragma mark - 根据文字计算高度宽度
+ (CGSize)getStringSize:(NSString *)str Width:(CGFloat )width Font:(UIFont *)font
{
    CGRect rect = [str
                   boundingRectWithSize:CGSizeMake(width, 0)
                   options:NSStringDrawingUsesLineFragmentOrigin
                   attributes:@{NSFontAttributeName:font}
                   context:nil];
    return rect.size ;
    
}
#pragma mark - 得到当前时间
+ (NSString *)getCurrentTimeWithFormat:(NSString *)format
{
    if (format == nil) format = @"yyyy-MM-dd";
    
    NSDate *d=[NSDate date];
    NSDateFormatter  *df=[[NSDateFormatter alloc] init];
    [df setDateFormat:format];
    return [df stringFromDate:d];
}
+ (void)setLabelAttributedWithLabel:(UILabel *)l string:(NSString *)s lineSpacing:(int)lineSpacing
{
    if (s == nil)  return ;
    if (lineSpacing == 0)  lineSpacing = 3 ;
    
    //拉宽label中行间距
    NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:s];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setLineSpacing:lineSpacing];
    [attribute addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, s.length)];
    [l setAttributedText:attribute];
}

// md5加密
+ (NSString *)md5Digest:(NSString*)string
{
    const char *original_str = [string UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(original_str, (CC_LONG)strlen(original_str), result);
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
        [hash appendFormat:@"%02X", result[i]];
    return [hash lowercaseString];
}

#pragma mark - 判断字符串是否为空
+ (BOOL)isEmptyString:(NSString *)string
{
    if (string == nil)  return YES;
    if (string == NULL)    return YES;
    if ([string isKindOfClass:[NSNull class]]) return YES;
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0) return YES;
    
    return NO;
}
#pragma mark - 获得省份列表
+(NSArray*)getPro
{
    NSBundle *mainBundle = [NSBundle mainBundle];
    //    获取txt文件路径
    NSString *txtPath = [mainBundle pathForResource:@"province" ofType:@"txt"];
    //    将txt到string对象中，编码类型为NSUTF8StringEncoding
    NSString *string = [[NSString  alloc] initWithContentsOfFile:txtPath encoding:NSUTF8StringEncoding error:nil];
    
    NSData *data= [string dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *error = nil;
    
    id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    
    if ([jsonObject isKindOfClass:[NSArray class]]){
        NSArray *pros = (NSArray*)jsonObject;
        return pros;
    }
    return nil;
}
#pragma mark - 获得城市列表
+(NSDictionary *)getCitys
{
    NSBundle *mainBundle = [NSBundle mainBundle];
    //    获取txt文件路径
    NSString *txtPath = [mainBundle pathForResource:@"city" ofType:@"txt"];
    //    将txt到string对象中，编码类型为NSUTF8StringEncoding
    NSString *string = [[NSString  alloc] initWithContentsOfFile:txtPath encoding:NSUTF8StringEncoding error:nil];
    
    NSData *data= [string dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *error = nil;
    
    id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    
    if ([jsonObject isKindOfClass:[NSDictionary class]]){
        NSDictionary *citys = (NSDictionary*)jsonObject;
        return citys;
    }
    return nil;
}
- (NSArray *)getCityArrayWithCode:(NSString *)code
{
    NSDictionary *cityDic = [PublicUtils getCitys];
    return [cityDic objectForKey:code];
}
-(void)getName:(NSString*)proCode
{
    NSDictionary *citysDic;
    NSArray *citys = [citysDic objectForKey:proCode];
    NSDictionary *cityDic = [citys objectAtIndex:0];
    [cityDic objectForKey:@"name"];
}


#pragma mark - 时间转换
+ (NSString *)timeToTime:(NSString *)time year:(BOOL)yesOrNo
{
    if (time == nil) return @"" ;
    
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    NSDate *date = [fmt dateFromString:time];
    
    NSTimeInterval delta = [[NSDate date] timeIntervalSinceDate:date];
    
    // 4.根据时间间隔算出合理的字符串
    if (delta < 60) { // 1分钟内
        return @"刚刚";
    } else if (delta < 60 * 60) { // 1小时内
        return [NSString stringWithFormat:@"%.f分钟前", delta/60];
    } else if (delta < 60 * 60 * 24) { // 1天内
        return [NSString stringWithFormat:@"%.f小时前", delta/60/60];
    } else if (delta < 60 *60 * 24 * 3){//3天内
        return [NSString stringWithFormat:@"%d天前",(int)delta/(60*60*24)];
    }else{
        return [time substringWithRange:yesOrNo ? NSMakeRange(0, 11) : NSMakeRange(5, 5)];
    }
}
//两个时间之差
- (NSString *)intervalFromLastDate: (NSString *) dateString1  toTheDate:(NSString *) dateString2
{
    NSArray *timeArray1=[dateString1 componentsSeparatedByString:@"."];
    dateString1=[timeArray1 objectAtIndex:0];
    
    
    NSArray *timeArray2=[dateString2 componentsSeparatedByString:@"."];
    dateString2=[timeArray2 objectAtIndex:0];
    
    NSDateFormatter *date=[[NSDateFormatter alloc] init];
    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *d1=[date dateFromString:dateString1];
    NSTimeInterval late1=[d1 timeIntervalSince1970]*1;

    NSDate *d2=[date dateFromString:dateString2];
    NSTimeInterval late2=[d2 timeIntervalSince1970]*1;
    
    NSTimeInterval cha=late2-late1;
    NSString *timeString=@"";
    NSString *house=@"";
    NSString *min=@"";
    NSString *sen=@"";
    
    sen = [NSString stringWithFormat:@"%d", (int)cha%60];
    //min = [min substringToIndex:min.length-7];
    //秒
    sen=[NSString stringWithFormat:@"%@", sen];
    
    min = [NSString stringWithFormat:@"%d", (int)cha/60%60];
    //min = [min substringToIndex:min.length-7];
    //    分
    min=[NSString stringWithFormat:@"%@", min];
    
    //    小时
    house = [NSString stringWithFormat:@"%d", (int)cha/3600];
    //house = [house substringToIndex:house.length-7];
    house=[NSString stringWithFormat:@"%@", house];
    
    
    timeString=[NSString stringWithFormat:@"%@:%@:%@",house,min,sen];
    
    return timeString;
}


//一个时间距现在的时间
- (NSString *)intervalSinceNow: (NSString *) theDate
{
    NSArray *timeArray=[theDate componentsSeparatedByString:@"."];
    theDate=[timeArray objectAtIndex:0];
    
    NSDateFormatter *date=[[NSDateFormatter alloc] init];
    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *d=[date dateFromString:theDate];
    
    NSTimeInterval late=[d timeIntervalSince1970]*1;
    
    
    NSDate* dat = [NSDate date];
    NSTimeInterval now=[dat timeIntervalSince1970]*1;
    NSString *timeString=@"";
    
    NSTimeInterval cha=late-now;
    
    if (cha/3600<1) {
        timeString = [NSString stringWithFormat:@"%f", cha/60];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"剩余%@分", timeString];
        
    }
    if (cha/3600>1&&cha/86400<1) {
        timeString = [NSString stringWithFormat:@"%f", cha/3600];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"剩余%@小时", timeString];
    }
    if (cha/86400>1)
    {
        timeString = [NSString stringWithFormat:@"%f", cha/86400];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"剩余%@天", timeString];
        
    }
    return timeString;
}


@end
